# Create your views here.
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.http import HttpResponse, Http404

from forfood.restaurant.models import Restaurant
from forfood.helpers.user_helper import *
from forfood.restaurant.forms import *
from forfood.menu.models import *
from forfood.comment.models import *
from forfood.customer.models import *
import datetime
import re

def administrator_comment_page(request):
    print("holy shit")
    customer = find_customer(request.user)
    print("xx")
    restaurant = find_restaurant(request.user)

    customers=Customer.objects.all()

    if 'user-comment-content' in request.GET and request.GET['user-comment-content'] \
        and 'user-id' in request.GET and request.GET['user-id']:
        comment_content = request.GET['user-comment-content']
        customer = Customer.objects.get(id=request.GET['user-id'])
        now = datetime.datetime.now()
        print("11")
        Comment.objects.create(comment_content=comment_content, datestamp=now, 
                               replied_comment_id=-1,customer=customer)
        print("12")
    
    if 'user-comment-reply-content' in request.GET and request.GET['user-comment-reply-content'] \
        and 'user-id' in request.GET  and request.GET['user-id'] and 'replied-comment-id' in request.GET \
        and request.GET['replied-comment-id']:
        handle_reply_comment(request)
      
    comments = Comment.objects.filter(restaurant=None).order_by('-datestamp')
    comment_count = comments.count 
        
    
    return render_to_response('comment/administrator_comment.html', RequestContext(request, locals()))
    

def handle_reply_comment(request):
    reply_comment_content = request.GET['user-comment-reply-content']
    comment_id = request.GET['replied-comment-id']
    customer = Customer.objects.get(id=request.GET['user-id'])
    
    now = datetime.datetime.now()
    
    if(re.search(r'//#', reply_comment_content)):
        comment=Comment.objects.get(id=comment_id)
        if (comment):
            index = reply_comment_content.find('//#', 0)
            i=0
            reply_comment=''
            while i < index:
                reply_comment=reply_comment+reply_comment_content[i]
                i=i+1 
            
            
            Comment.objects.create(comment_content=reply_comment, datestamp=now, 
                               replied_comment_id=comment_id, restaurant=None,customer=customer)
        else:
            Comment.objects.create(comment_content=reply_comment_content, datestamp=now, 
                               replied_comment_id=-1, restaurant=None,customer=customer)
    else:
        Comment.objects.create(comment_content=comment_content, datestamp=now, 
                               replied_comment_id=-1, restaurant=None,customer=customer)